package com.jian.mall.common.exception;

import com.jian.mall.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;

@Slf4j
@RestControllerAdvice(basePackages = "com.jian.mall.produce.controller")
public class ValidationException {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R MyValidationExceptionAdvice(MethodArgumentNotValidException e ){
        log.error("Exception: {} \n----- ExceptionType: {}",e.getMessage(),e.getClass());
        BindingResult bindingResult = e.getBindingResult();
        HashMap<String, String> errorMap = new HashMap<>();
        bindingResult.getFieldErrors().forEach((item)->{
            errorMap.put(item.getField(),item.getDefaultMessage());
        });
        return R.error().put("error",errorMap);
    }
}
